import logging
import cgi
import os
import datetime

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from droidguide_classes import *

def printUserActivity(self, userActivity):
      printObjectShort(self, userActivity)
      activity = getObject(userActivity.activity_key)
      landmark = getObject(activity.landmark_id)
      self.response.out.write(landmark.to_xml())
      self.response.out.write(activity.to_xml())     

#http://localhost:8080/activity/process?operation=create&lat=-19.848425&long=-43.971577&name=museum%20of%20art&desc=museum%20of%20art%20at%20pampulha%20constructed%20in%201935&signature=1,9,4,0,8,0
def createActivity(self):
      lat = float(self.request.get('lat'))
      long = float(self.request.get('long'))
      name = self.request.get('name')
      desc = self.request.get('desc')
      signature = self.request.get('signature')
      landmark_key = self.request.get('landmark_key')
#      print 'lat %f' % lat
#      print 'long %f' % long
      
      if landmark_key:
	      landmark = getObject(landmark_key)
#	      if not landmark:
#              addMessage('landmark not found', self)
      else:
	      landmark = Landmark()
	      landmark.title = name
	      landmark.description = desc
	      landmark.lat = lat
	      landmark.lon = long
	      landmark.put()

      activity = DroidGuideActivity()
      activity.landmark_id = str(landmark.key())
      activity.signature = signature
      activity.put()

      self.response.out.write(landmark.to_xml())
      self.response.out.write(activity.to_xml())

#http://localhost:8080/activity/process?operation=list&droidGuideUser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw
def listActivities(self):      
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      if droidGuideUser_key:
          q = UserActivity.gql("WHERE droidGuideUser_key = :dgkey",
               dgkey=droidGuideUser_key)
	  results = q.fetch(100)
	  for result in results:
	      printUserActivity(self, result)
      else:
          q = DroidGuideActivity.all()
	  results = q.fetch(100)
	  for activity in results:
	      landmark = getObject(activity.landmark_id)
	      if landmark:
                  self.response.out.write(landmark.to_xml())
                  self.response.out.write(activity.to_xml())


def createSignatureFromProfile(profile):
#              print 'no signature'
              signature = str(profile.consumer) + ',' + str(profile.historical) + ',' + str(profile.ecological) + ',' + str(profile.gastronomic) + ',' + str(profile.cultural) + ',' + str(profile.bohemian)
              profile.signature = signature
              profile.put()
#              print 'signature profile2 %s' % signature
              return signature

def checkActivitySignature(profile, activity):
      signature = activity.signature
      v = signature.split(',')
      consumer = int(v[0])
      historical = int(v[1])
      ecological = int(v[2])
      gastronomic = int(v[3])
      cultural = int(v[4])
      bohemian = int(v[5])
      landmark = getObject(activity.landmark_id)
      # check if activity has a valid landmark
      logging.debug('activity signature %s' % signature)
      logging.debug('profile  signature %s' % profile.signature)

      if not landmark:
          return False
      # if the signature is close to the user's interests
#             print 'consumer %d ' % abs(consumer - profile.consumer)
#             print 'historical %d ' % abs(historical - profile.historical)
#             print 'ecological %d ' % abs(ecological - profile.ecological)
#             print 'gastronomic %d ' % abs(gastronomic - profile.gastronomic)
#             print 'cultural %d ' % abs(cultural - profile.cultural)
#             print 'bohemian %d ' % abs(bohemian - profile.bohemian)
      absConsumer = consumer - profile.consumer
      logging.debug('absConsumer %s' % absConsumer)
      absHistorical = abs(historical - profile.historical)
      logging.debug('absHistorical %s' % absHistorical)
      absEcological = abs(ecological - profile.ecological)
      logging.debug('absEcological %s' % absEcological)
      absGastronomic = abs(gastronomic - profile.gastronomic)
      logging.debug('absGastronomic %s' % absGastronomic)
      absBohemian = abs(bohemian - profile.bohemian)
      logging.debug('absBohemian %s' % absBohemian)
      absCultural = abs(cultural - profile.cultural)
      logging.debug('absCultural %s' % absCultural)

      isConsumer = absConsumer <= ACTIVITY_SIGNATURE_THRESHOLD
      logging.debug('isConsumer %s' % isConsumer)
      isHistorical = absHistorical <= ACTIVITY_SIGNATURE_THRESHOLD
      logging.debug('isHistorical %s' % isHistorical)
      isEcological = absEcological <= ACTIVITY_SIGNATURE_THRESHOLD
      logging.debug('isEcological %s' % isEcological)
      isGastronomic = absGastronomic <= ACTIVITY_SIGNATURE_THRESHOLD
      logging.debug('isGastronomic %s' % isGastronomic)
      isCultural = absCultural <= ACTIVITY_SIGNATURE_THRESHOLD
      logging.debug('isCultural %s' % isCultural)
      isBohemian = absBohemian <= ACTIVITY_SIGNATURE_THRESHOLD
      logging.debug('isBohemian %s' % isBohemian)

      resultado = isConsumer and isHistorical and isEcological and isGastronomic and isCultural and isBohemian
      return resultado


#http://localhost:8080/activity/process?operation=getForUser&droidGuideuser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw
def getActivitiesForUser(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      q = UserActivity.gql("WHERE droidGuideUser_key = :dgkey",
           dgkey=droidGuideUser_key)
      if q:
          results = q.fetch(100)
          for result in results:
              result.delete()
          
      profile = getProfileForUser(self)
      L = []
      if profile:
          logging.debug('found profile for user: %s' % str(profile.key()))
          signature = profile.signature
          if not signature:
	      signature = createSignatureFromProfile(profile)
          logging.debug('signature: %s' % profile.signature)
          q2 = DroidGuideActivity.all()
          logging.debug('found %d activities for user' % q2.count())
	  # for each activity that exists in the system
	  for activity in q2:
              if checkActivitySignature(profile, activity):
                  logging.debug('found activity %s' % activity.signature)
	          L.append(activity)
	  # for each activity found
	  index = 0
          for a in L:
	      # search for user activities that already exist
	      activity_key = str(a.key())
              q = UserActivity.gql("WHERE droidGuideUser_key = :dgkey and activity_key = :act_key",
                  dgkey=droidGuideUser_key, act_key=activity_key)
	      userActivity = q.get()
	      index = index + 1	      
	      if not userActivity:
	          # create new user activity for user
		  userActivity = UserActivity()
  	          userActivity.droidGuideUser_key = droidGuideUser_key
	          userActivity.activity_key = str(a.key())
	          userActivity.state = 'created'
	          userActivity.index = index
	          userActivity.put()
	          index = index + 1
              printUserActivity(self, userActivity)
      else:
          # user has no profile
	  addMessage('user has no profile yet', self)

#http://localhost:8080/activity/process?operation=getForUser&droidGuideuser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw
def getActivitiesForUserOld(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      q = UserActivity.gql("WHERE droidGuideUser_key = :dgkey",
           dgkey=droidGuideUser_key)
      
      if q:
          results = q.fetch(100)
          for result in results:
              if result.state == 'finished':
                  result.delete()
          
      profile = getProfileForUser(self)
      L = []
      if profile:
#          print 'got profile'
          signature = profile.signature
#          print 'signature profile1 %s' % signature
          if not signature:
	      signature = createSignatureFromProfile(profile)
          q2 = DroidGuideActivity.all()
#          print 'getting all activities'
	  # for each activity that exists in the system
	  for activity in q2:
              if checkActivitySignature(profile, activity):
	          L.append(activity)
	  # for each activity found
	  index = 0
          for a in L:
	      # search for user activities that already exist
	      activity_key = str(a.key())
#	      print 'activity %s' %  activity_key
              q = UserActivity.gql("WHERE droidGuideUser_key = :dgkey and activity_key = :act_key",
                  dgkey=droidGuideUser_key, act_key=activity_key)
	      userActivity = q.get()
	      index = index + 1	      
	      if not userActivity:
	          # create new user activity for user
		  userActivity = UserActivity()
  	          userActivity.droidGuideUser_key = droidGuideUser_key
	          userActivity.activity_key = str(a.key())
	          userActivity.state = 'created'
	          userActivity.index = index
	          userActivity.put()
	          index = index + 1
              printUserActivity(self, userActivity)
      else:
          # user has no profile
	  addMessage('user has no profile yet', self)

#http://localhost:8080/activity/process?operation=subscribe&droidGuideUser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw
def subscribeActivitiesForUser(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      q = UserActivity.gql("WHERE droidGuideUser_key = :dgkey",
           dgkey=droidGuideUser_key)
      for userActivity in q:
          userActivity.state = 'to be executed'
          userActivity.put()
          printUserActivity(self, userActivity)

#http://localhost:8080/activity/process?operation=subscribe&droidGuideUser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw
def subscribeActivityForUser(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      userActivity_key = self.request.get('userActivity_key')
      if userActivity_key:
          userActivity = getObject(userActivity_key)
          userActivity.state = 'to be executed'
          userActivity.put()
          printUserActivity(self, userActivity)

#http://localhost:8080/activity/process?operation=subscribe&droidGuideUser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw
def unsubscribeActivityForUser(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      userActivity_key = self.request.get('userActivity_key')
      if userActivity_key:
          userActivity = getObject(userActivity_key)
          userActivity.state = 'canceled'
          userActivity.put()
          printUserActivity(self, userActivity)

#http://localhost:8080/activity/process?operation=update&userActivity_key=agpkcm9pZGd1aWRlchMLEgxVc2VyQWN0aXZpdHkY_gIM&new_state=in%20execution
def updateActivity(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      userActivity_key = self.request.get('userActivity_key')
      new_state = self.request.get('new_state')
      userActivity = getObject(userActivity_key)
      if userActivity:
          userActivity.state = new_state
          userActivity.put()
          printUserActivity(self, userActivity)

def getActivitiesByState(self):
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      state = self.request.get('state')
      q = None
      if droidGuideUser_key:
	      q = UserActivity.gql("WHERE droidGuideUser_key = :dgkey and state = :st",
             dgkey=droidGuideUser_key, st=state)
      else:
	      q = UserActivity.gql("WHERE state = :st",
             st=state)
      for userActivity in q:
          printUserActivity(self, userActivity)
          
#http://localhost:8080/user_profile/save?name=waldir&gender=M&birth_year=1976&marital_status=M&food=1&drink=0&style=T&consumer=1&historical=8&ecological=7&gastronomic=1&cultural=7&bohemian=0&weather=0&traffic=0&droidGuideuser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw


class Process(webapp.RequestHandler):
  def get(self):
      
      operation = self.request.get('operation')

      startDroidGuideMessage(self)

      if operation == 'create':
          createActivity(self)

      # http://localhost:8080/activity/process?operation=deleteAll
      elif operation == 'deleteAll':
          deleteAll(Landmark)

      elif operation == 'list':
          listActivities(self)

      elif operation == 'listLandmarks':
          listObjects(Landmark, self)

      elif operation == 'listActivities':
          listObjects(DroidGuideActivity, self)

      #http://localhost:8080/activity/process?operation=listUserActivities
      elif operation == 'listUserActivities':
          listObjects(UserActivity, self)

      #http://localhost:8080/activity/process?operation=listProfiles
      elif operation == 'listProfiles':
          listObjectsFromQuery(UserProfile.all(), self)
          
      #http://localhost:8080/activity/process?operation=deleteProfiles
      elif operation == 'deleteProfiles':
          deleteAll(UserProfile)
          
      #http://localhost:8080/activity/process?operation=getForUser&droidGuideUser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchjwAgw
      elif operation == 'getForUser':
          getActivitiesForUser(self)

      elif operation == 'subscribe':
          subscribeActivitiesForUser(self)
          
      elif operation == 'subscribeActivity':
          subscribeActivityForUser(self)

      elif operation == 'unsubscribeActivity':
          unsubscribeActivityForUser(self)

      elif operation == 'deleteActivities':
          deleteAll(UserActivity)
          
      elif operation == 'deleteDroidGuideActivities':
          deleteAll(UserActivity)
          
      elif operation == 'update':
          updateActivity(self)
          
      #http://localhost:8080/activity/process?operation=getByState&state=created
      elif operation == 'getByState':
          getActivitiesByState(self)
          
      finishDroidGuideMessage(self)

application = webapp.WSGIApplication([('/activity/process', Process)], debug=True)


def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
